package cn.com.ctcloud.saas.ids.demo.user.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.ctcloud.saas.ids.demo.user.dao.IUserDemoDao;
import cn.com.ctcloud.saas.ids.demo.user.domain.UserDemoObj;
import cn.com.ctcloud.saas.ids.demo.user.service.IUserDemoService;

/**
 * Title: ChinaCT IDS
 * <p>
 * Description: Demo
 * <p>
 * Copyright: Copyright (c) 2008
 * <p>
 * Company: Liaoning Open Data Communication Co.,Ltd.
 *
 * @author lihui
 * @version 2.0.0
 */
@Service
public class UserDemoServiceImpl implements IUserDemoService {
	@Autowired
	private IUserDemoDao userDao;

	/**
	 * 保存对象
	 *
	 * @param obj
	 *            对象
	 */
	@Override
	public void saveOrUpdate(final UserDemoObj obj) {
		if (obj == null) {
			return;
		}
		final UserDemoObj oldObj = userDao.getByLogicId(obj.getLogicId());

		// 有ID的话要判断是否保存还是更新
		if (oldObj == null) {
			// 保存
			this.setForm(obj, obj);

			userDao.save(obj);

		} else {
			// 更新
			this.setForm(obj, oldObj);

			userDao.update(oldObj);
		}
	}

	/**
	 * 根据ID删除对象
	 *
	 * @param logicId
	 *            对象ID
	 */
	@Override
	public void deleteByLogicId(final String logicId) {
		if (StringUtils.isEmpty(logicId)) {
			return;
		}

		final UserDemoObj obj = userDao.getByLogicId(logicId);
		if (obj == null) {
			return;
		}

		userDao.deleteByLogicId(logicId);
	}

	/**
	 * 根据id查询对象
	 *
	 * @param logicId
	 *            对象logicId
	 * @return 对象
	 */
	@Override
	public UserDemoObj getByLogicId(final String logicId) {
		if (StringUtils.isEmpty(logicId)) {
			return null;
		}
		return userDao.getByLogicId(logicId);
	}

	/**
	 * 查询所有对象
	 *
	 * @return 对象集合
	 */
	@Override
	public List<UserDemoObj> findAll() {
		return userDao.findAll();
	}

	/**
	 * 复制信息
	 *
	 * @param fromObj
	 *            原信息
	 * @param toObj
	 *            新信息
	 */
	private void setForm(final UserDemoObj fromObj, final UserDemoObj toObj) {
		toObj.setName(StringUtils.trimToEmpty(fromObj.getName()));
		toObj.setPwd(StringUtils.trimToEmpty(fromObj.getPwd()));
		toObj.setAge(fromObj.getAge());
		toObj.setEmail(StringUtils.trimToEmpty(fromObj.getEmail()));
	}

}